﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Mvc;
using System.Web.Mvc.Html;

namespace MVCToolkit.Controls
{
    public static class FormExtensions
    {
        public static MvcForm KOBeginForm(this HtmlHelper htmlHelper, 
            object htmlAttributes = null,
            object koBindAttributes = null)
        {
            IDictionary<string, object> htmlAttributesDictionary = null;

            if (htmlAttributes != null)
            {
                htmlAttributesDictionary = HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes);
            }
            else
            {
                htmlAttributesDictionary = new Dictionary<string, object>();
            }

            if (koBindAttributes != null)
            {
                StringBuilder dataBindCustomValues = new StringBuilder();
                foreach (var dataItem in HtmlHelper.AnonymousObjectToHtmlAttributes(koBindAttributes))
                {
                    dataBindCustomValues.Append(dataItem.Key);
                    dataBindCustomValues.Append(":");
                    dataBindCustomValues.Append(dataItem.Value);
                    dataBindCustomValues.Append(",");
                }
                htmlAttributesDictionary.Add("data-bind", dataBindCustomValues.ToString().TrimEnd(','));
            }

            //htmlAttributesDictionary.Add("action", "/");

            return htmlHelper.BeginForm(null, null, FormMethod.Post, htmlAttributesDictionary);

        }
    }
}
